import type { EventBindingConfig } from '../../lib/abstract/base_destructible'
import type { IUserCenterModule } from '../../types/interfaces'
import { DescriptionList } from '../../components/description_list'
import { GMStorage } from '../../lib/abstract'
import { ThemeVarService } from '../../lib/abstract/style/theme_var/service'
import { ToolKit } from '../../lib/utils/toolkit'
import {
  BUILD_CONFIG,
  BUTTON_STYLES,
  LOCAL_STORAGE_KEYS,
  PROJECT_PREFIX,
} from '../../types/constants'
import { StylesService } from '../../types/constants/styles'
import { BASE_LINK_COLOR, SYMBOLS } from '../../types/interfaces'

export class About extends GMStorage implements IUserCenterModule {
  id: string = 'about'
  name: string = 'About'
  private readonly isLatest: boolean
  private static instance: About
  protected readonly themeVarService: ThemeVarService = ThemeVarService.getInstance()
  private readonly stylesService: StylesService = StylesService.getInstance()
  private supportedLatest = false // 预留支持最新版本检测功能

  constructor() {
    super()

    this.isLatest = 'isLatest' in GM_info ? GM_info.isLatest as boolean : false
  }

  /**
   * 获取单例实例
   */
  public static getInstance(): About {
    if (!About.instance) {
      About.instance = new About()
    }
    return About.instance
  }

  public generateHTML(): string {
    const list = new DescriptionList({
      themeColor: BASE_LINK_COLOR.PRIMARY,
    })

    // 添加描述项
    list.addItems([
      {
        label: '脚本主页',
        content: `<a href="${BUILD_CONFIG.URL.HOMEPAGE_URL}" target="_blank" rel="noopener noreferrer" class="description-link">访问主页</a>`,
      },
      {
        label: '作者名称',
        content: GM_info.script.author!,
      },
      {
        label: '当前版本',
        content: `v${GM_info.script.version!}`,
      },
      {
        label: '描述信息',
        content: GM_info.script.description!,
      },
      {
        label: '更新配置',
        content: GM_info.scriptWillUpdate ? '自动更新已启用' : '自动更新未配置',
        className: GM_info.scriptWillUpdate ? 'update-enabled' : 'update-disabled',
      },
      {
        label: '上次更新',
        content: ToolKit.time.getFullTimeDescription(GM_info.script.lastModified || 0),
      },
    ])

    if (this.supportedLatest && !this.isLatest && GM_info.script.downloadURL) {
      list.addItem({
        label: '版本更新',
        content: `
          <div class="update-available">
            <span>检测到新版本可用！</span>
            <button class="update-btn" id="updateNowBtn">
              立即更新
            </button>
          </div>
        `,
        className: 'update-available-item',
      })
    }

    return `
      <div class="about-container">
        <div class="about-actions">
          <button class="btn ${BUTTON_STYLES.secondary.className} reset-btn">
            重置脚本
          </button>
        </div>
      
        <div class="about-header">
          <span class="about-icon"><img src="${BUILD_CONFIG.IMAGE.LOGO_URL}" alt="home-icon" width="24" height="24"></span>
          <h3 class="about-title">${GM_info.script.name}</h3>
        </div>
        
        ${list.render()}

        <div class="about-footer">
          <a class="about-link" href="${BUILD_CONFIG.URL.VERSIONS_URL}" target="_blank" rel="noopener noreferrer">
            ${SYMBOLS.TIME.HOURGLASS} 查看更新历史
          </a>
        </div>
      </div>
    `
  }

  get eventConfigs(): EventBindingConfig[] {
    return [
      {
        enabled: this.supportedLatest && !this.isLatest,
        selector: '#updateNowBtn',
        eventType: 'click',
        handler: (_e: any) => this.handleClickUpdateBtn(),
        meta: { category: 'update' },
      },
      {
        selector: '.about-actions .reset-btn',
        eventType: 'click',
        handler: (_e: any) => this.handleClickResetBtn(),
        meta: { category: 'reset' },
      },
    ]
  }

  public handleOpen = (): void => {
    this.autoBindEvents(true)
  }

  /**
   * 处理点击更新按钮事件
   */
  private handleClickUpdateBtn(): void {
    if (GM_info.script.downloadURL) {
      ToolKit.browser.url.openNewTab(GM_info.script.downloadURL!)
    }
  }

  /**
   * 处理点击重置按钮事件
   */
  private handleClickResetBtn(): void {
    this.storage.empty()
    Object.values(LOCAL_STORAGE_KEYS).forEach((key) => {
      localStorage.removeItem(key)
    })
    ToolKit.ui.page.refreshPage()
  }

  destroy(): void {
    document.getElementById('updateNowBtn')?.removeEventListener('click', this.handleClickUpdateBtn)
  }

  /**
   * 样式
   */
  public styles(): string {
    return `/* =============================== 【脚本详情】 =============================== */
      .about-container {
        all: initial !important;
        color: #333;
        max-width: 100%;
        padding: 0 10px;
        
        /* 头部样式 */
        .about-header {
          display: flex;
          align-items: center;
          color: #545454 !important;
          margin-bottom: 15px;
          padding-bottom: 10px;
          
          .about-icon {
            font-size: 1.5em;
            margin-right: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
          }
          
          .about-title {
            margin: 0;
            font-size: 1.2em;
            color: var(--${PROJECT_PREFIX}-theme-text-primary) !important;
            font-weight: bold;
          }
        }
        
        /* 操作按钮样式 */
        .about-actions {
          display: flex;
          align-items: center;
          justify-content: flex-end;
          gap: 6px;
        }
        
        /* 链接样式 */
        .description-link {
          ${this.stylesService.link.default()}
        }
        
        /* 更新按钮样式 */
        .update-btn {
          margin-left: 10px;
          padding: 4px 12px;
          background-color: ${BASE_LINK_COLOR.PRIMARY};
          color: white;
          border: none;
          border-radius: 4px;
          cursor: pointer;
          font-size: 12px;
          transition: all 0.2s;
        }
        
        .update-btn:hover {
          background-color: ${BASE_LINK_COLOR.PRIMARY_DARK};
          transform: translateY(-1px);
        }
        
        /* 更新状态样式 */
        .update-enabled {
          color: #27ae60 !important;
        }
        
        .update-disabled {
          color: #e74c3c !important;
        }
        
        .update-available {
          color: #f39c12;
          display: flex;
          align-items: center;
          font-weight: 500;
        }
        
        /* 页脚链接 */
        .about-footer {
          margin-top: 15px;
          text-align: center;
          padding-top: 10px;
        }
        
        .about-link {
          ${this.stylesService.link.default()}
        }
      }
    `
  }
}
